package com.myslef.teaching_platfrom.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.myslef.teaching_platfrom.common.R;
import com.myslef.teaching_platfrom.domain.users.User;
import com.myslef.teaching_platfrom.service.UserService;
import com.myslef.teaching_platfrom.utils.CodeRandom;
import com.myslef.teaching_platfrom.utils.JwtUtils;
import com.myslef.teaching_platfrom.utils.MailUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@CrossOrigin
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${upload.dir}") // 读取配置文件中的上传文件保存目录
    private String uploadDir;


    @PostMapping("/login")
    public R<User> login(HttpServletRequest request, @RequestBody User user){

        //1、将页面提交的密码password进行md5加密处理
        String password = user.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        User u;
        queryWrapper.eq(User::getEmail,user.getEmail()).eq(User::getLevel,user.getLevel());
        u = userService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(u == null){
            return R.error("登录失败，账号错误");
        }

        //4、密码比对，如果不一致则返回登录失败结果
        if(!u.getPassword().equals(password)){
            return R.error("登录失败，密码错误");
        }
        //5、登录成功，将员工id存入Session并返回登录成功结果
        String token = JwtUtils.generateToken(u.getEmail());
        return R.success(u, token);
    }


    @PostMapping("/regist")
    public R register(@RequestBody User user) {
        String password = user.getPassword();
        String email = user.getEmail();
        String userName = user.getUserName();
        String uid = user.getUid();
        Integer level = user.getLevel();

        //2、根据页面提交的email查询数据库
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,user.getEmail());

        User u = userService.getOne(queryWrapper);

        if(u != null){
            return R.error("该邮件已被注册!");
        }
        queryWrapper.clear();
        queryWrapper.eq(User::getUserName,user.getUserName());
        u = userService.getOne(queryWrapper);
        if(u != null){
            return R.error("该用户名已被注册!");
        }

        queryWrapper.clear();
        queryWrapper.eq(User::getUid,user.getUid());
        u = userService.getOne(queryWrapper);
        if(u != null){
            return R.error("该工号/学号已被注册!");
        }
        u = new User();
        // 使用MD5技术加密
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        u.setPassword(password);
        u.setEmail(email);
        u.setUserName(userName);
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        u.setCreateTime(timestamp);
        u.setUpdate_time(timestamp);
        u.setLevel(level);
        u.setPicUrl("uploads/portrait/init.jpg");
        u.setUid(uid);
        boolean flag = userService.save(u);
        if(!flag){
            return R.error("出错了！！！");
        }
        return R.success("成功了!");
    }

    /**
     * 获取验证码
     * @param user
     * @return
     */
    @PostMapping("captcha")
    public R getCaptcha(@RequestBody User user){

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail,user.getEmail());
        User u = userService.getOne(queryWrapper);
        if(u == null){
            return R.error("用户不存在，请先注册");
        }
        String email = user.getEmail();
        try {
            Object code = redisTemplate.opsForValue().get(email);
            if(code == null || "".equals(code)){
                code = CodeRandom.verifyCode(6);
            }
            redisTemplate.opsForValue().set(email,(String) code,5, TimeUnit.MINUTES);
            MailUtils.sendMail(email, (String) code);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success("手机验证码发送成功！");
    }

    @PostMapping("isCaptcha")
    public R isCaptcha(@RequestBody Map map){
        System.out.println(map.toString());
        String email = map.get("email").toString();
        String captcha = map.get("captcha").toString();

        //从redis获取验证码
        Object code = redisTemplate.opsForValue().get(email);
        if(captcha != null && captcha.equals(code)){
            //对比成功返回成功
            redisTemplate.delete(email);
            return R.success("密码正确");
        }
        return R.error("密码错误");
    }

    @PostMapping("updatePassword")
    public R updatePassword(@RequestBody User user){
        Integer u = userService.updateUserPassword(user.getEmail(), user.getPassword());
        if(u > 0){
            return R.success("修改成功");
        }
        return R.error("修改失败");
    }


    @PostMapping("/upload/{id}")
    public R uploadImage(@PathVariable Integer id, @RequestParam("file") MultipartFile file) {
        try {
            // 获取上传的文件名和文件扩展名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            System.out.println(originalFileName +"," + fileExtension);
            // 生成新的文件名
            String newFileName =id.toString()+"_" + System.currentTimeMillis() + "." + fileExtension;

            // 创建上传目录
            Path uploadPath = Paths.get(uploadDir+"/portrait");
            if (!Files.exists(uploadPath)) {
                try {
                    Files.createDirectories(uploadPath);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 保存上传的文件
            Path filePath = Paths.get(uploadDir+"/portrait", newFileName);
            Files.write(filePath, file.getBytes());

            LambdaUpdateWrapper<User> updateWrapper= new LambdaUpdateWrapper<>();
            updateWrapper.eq(User::getId, id).set(User::getPicUrl, filePath.toString());
            userService.update(updateWrapper);
            System.out.println(filePath);

            // 返回上传成功信息
            return R.success("上传成功！");
        } catch (IOException e) {
            // 返回上传失败信息
            return R.error("上传失败：" + e.getMessage());
        }
    }


    @GetMapping("/image/{id}")
    public ResponseEntity<byte[]> getImage(@PathVariable Integer id) throws IOException {
        // 从数据库中获取图片路径
        User user = userService.getById(id);
        // 读取图片文件到内存中
        File file = new File(user.getPicUrl());
        InputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes);
        inputStream.close();
        // 设置HTTP响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        // 返回图片内容给前端
        return new ResponseEntity<>(bytes, headers, HttpStatus.OK);
    }

    @GetMapping("/allUser")
    public R getAllUser(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(User::getId, User::getUserName);
        List<User> list = userService.list(queryWrapper);
        return R.success(list);
    }

    @GetMapping("/searchUser")
    public R getSearchUser(){
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(User::getId, User::getUserName);
        List<User> list = userService.list(queryWrapper);
        return R.success(list);
    }


    @PostMapping("/test")
    public R save(){
        System.out.println("1111");
        return R.success("11121");
    }

    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前登录员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    @PostMapping("/updateName")
    public R updateName(@RequestBody User user){
        LambdaUpdateWrapper<User> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, user.getId()).set(User::getUserName, user.getUserName());
        userService.update(updateWrapper);
        return R.success("更改成功");
    }
    @PostMapping("/updateSex")
    public R updateSex(@RequestBody User user){
        LambdaUpdateWrapper<User> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.eq(User::getId, user.getId()).set(User::getSex, user.getSex());
        userService.update(updateWrapper);
        return R.success("更改成功");
    }

//    @PostMapping("/uploads")
    public ResponseEntity<String> uploadImages(@RequestParam("file") MultipartFile file) {
        try {
            // 获取上传的文件名和文件扩展名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);

            // 生成新的文件名
            String newFileName = System.currentTimeMillis() + "." + fileExtension;

            // 创建上传目录
            Path uploadPath = Paths.get(uploadDir+"/portrait");
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 保存上传的文件
            Path filePath = Paths.get(uploadDir, newFileName);
            Files.write(filePath, file.getBytes());

            System.out.println(uploadDir + newFileName);
            // 返回上传成功信息
            return ResponseEntity.ok().body("上传成功！");
        } catch (IOException e) {
            // 返回上传失败信息
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败：" + e.getMessage());
        }
    }


}

